<!DOCTYPE html>

<html>
<!-- video 后置摄像头拍照 上传到服务器 可以返回重拍 -->
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<meta http-equiv="X-UA-Compatible" content="ie=edge">
		<title>摄像头拍照</title>
        <script src="jquery-3.3.1.min.js"></script>
		<style type="text/css">
			#video {
				object-fit: cover;
				object-position: center center;
			}
			
			#capture {
				width: 100px;
				height: 100px;
				border-radius: 50%;
				opacity: 0.5;
				position: fixed;
				left: calc(50% - 50px);
				left: -webkit-calc(50% - 50px);
				left: -moz-calc(50% - 50px);
				bottom: 40px;
			}
			#reset {
				width: 50px;
				height: 50px;
				border-radius: 50%;
				opacity: 0.5;
				position: fixed;
				left: calc(50% - 25px);
				left: -webkit-calc(50% - 25px);
				left: -moz-calc(50% - 25px);
				bottom: 20px;
				display: none;
			}
			.loading_pic{
				display: none;
			}
		</style>
	</head>
	 <body>
	    <img class="loading_pic" src="loading.gif" width="100%" height="auto" alt="">
		<div>
			<video id="video" width="100%" height="100%" controls="controls" webkit-playsinline='true' playsinline='true' x-webkit-airplay='true' x5-video-player-type='h5' x5-video-player-fullscreen='true' x5-video-ignore-metadata='true' width='100%' height='100%'>
			</video>
		</div>
		<br/>
		<div>
			<input type="button" title="开启摄像头" value="拍照识别" id="capture" />
		</div>
		<canvas id="canvas"></canvas>
		<p class="img_wrap"></p>
		<input type="button"  value="重拍" id="reset" />
	<script>
		window.onload = function() {
			//访问用户媒体设备的兼容方法
			function getUserMedia(constraints, success, error) {
				if(navigator.mediaDevices.getUserMedia) {
					//最新的标准API
					navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
				} else if(navigator.webkitGetUserMedia) {
					//webkit核心浏览器
					navigator.webkitGetUserMedia(constraints, success, error)
				} else if(navigator.mozGetUserMedia) {
					//firfox浏览器
					navigator.mozGetUserMedia(constraints, success, error);
				} else if(navigator.getUserMedia) {
					//旧版API
					navigator.getUserMedia(constraints, success, error);
				}
			}
			/*

			var exArray = []; //存储设备源ID

			MediaStreamTrack.getSources(function (sourceInfos) {

			for (var i = 0; i != sourceInfos.length; ++i) {

			var sourceInfo = sourceInfos[i];

			//这里会遍历audio,video，所以要加以区分

			if (sourceInfo.kind === 'video') {

			exArray.push(sourceInfo.id);

			}

			}

			});

			*/

			let video = document.getElementById('video');
			let canvas = document.getElementById('canvas');
			let context = canvas.getContext('2d');

			function success(stream) {
				//兼容webkit核心浏览器
				let CompatibleURL = window.URL || window.webkitURL;
				//video.src = CompatibleURL.createObjectURL(stream);
				video.srcObject = stream;
				video.play();
			}

			function error(error) {
				console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
			}

			 

			if(navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia) {
				if(!navigator.mediaDevices || !navigator.mediaDevices.enumerateDevices) {
					console.log("enumerateDevices() not supported.");
					return;
				}

				 

				// 列出摄像头和麦克风
				var exArray = [];
				navigator.mediaDevices.enumerateDevices()
					.then(function(devices) {
						devices.forEach(function(device) {
							console.log(device.kind + ": " + device.label +
								" id = " + device.deviceId);
							if(device.kind == "videoinput") {
								alert(device.label);
								exArray.push(device.deviceId);
							}
						});

						var mediaOpts = {

						};
						var mediaOpts = {
							video: {
								deviceId: {
									exact: exArray[1]
								}
							}
						};

						//调用用户媒体设备, 访问摄像头
						getUserMedia(mediaOpts, success, error);

					})
					.catch(function(err) {
						console.log(err.name + ": " + err.message);
					});
			} else {
				alert('不支持访问用户媒体');
			}
            var img = new Image();

			document.getElementById('capture').addEventListener('click', function() {
				var s = $("#video").outerWidth();
				var e = $("#video").outerHeight();
				$("#canvas").attr("width",s);
				$("#canvas").attr("height",e);
                context.drawImage(video, 0, 0, s, e);
                var dataUrl = canvas.toDataURL('image/jpeg', 1);
                $("#canvas").hide();
                $(".loading_pic").show();
                $("#video").hide();
                $("#capture").hide();
                $("#reset").hide();
                $(".img_wrap").hide();


                $.ajax({
                type: 'POST',
                url: "http://xxxxxx",
                data: { "xxx": dataUrl },
                dataType:'json',
                success: function (res) {
                    $(".loading_pic").hide();
                    $('.loading_pic').hide();
                    if (res.code == '200') {
                        $(".img_wrap").html(JSON.stringify(res.msg));
                        $("#video").hide();
                        $("#capture").hide();
                        $("#reset").show();
                        $(".img_wrap").show();
                    } else {
                        $("#video").show();
                        $(".img_wrap").hide();
                        $("#capture").show();
                        alert(JSON.stringify(res.msg));
                    }
                },
                error: function (err) {
                    $(".loading_pic").hide();
                    $('.loading_pic').hide();
                    $("#video").show();
                    $("#capture").show();
                    $(".img_wrap").hide();
                    alert(JSON.stringify(err));
                }

            });
			})
			document.getElementById('reset').addEventListener('click', function() {
				window.location.href=window.location.href;
			});
		}
	</script>

	</body>

</html>